const express = require('express');
const userTable = require('../../db/user/userTable')
const userDetailTable = require('../../db/user/userDetailTable')
const tipOffTable = require('../../db/tip-off/tipOffTable')
const tipOffCommentTable = require('../../db/tip-off/tipOffCommentTable')
const { v4 } = require('uuid');

// 举报服务
const tip_off_App = express()

// 鉴权的时候就把用户信息缓存起来 后续就不必再查数据库了
let userData = {}

// 操作鉴权
tip_off_App.all('/*', async (req, res, next) => {
  let permission = await userTable.find({ token: req.headers.authorization })
  if (permission.length) {
    userData = permission[0]
    next()
  } else {
    res.send({
      status: 403,
      message: '无操作权限'
    })
  }
})

// 文章举报处理
tip_off_App.post('/article', async (req, res) => {
  const { blogId, description, author_id, title, cover, reason } = req.body
  const tipOffId = v4()
  // 举报处理
  const tip =  await tipOffTable.create({
    tipOffId, blogId, author_id, description, title, cover, reason
  })

  if (!tip) return res.send({ status: 500, message: '举报失败！' })
  
  res.send({status: 200,message: '举报成功！'})
})

// 评论或回复举报处理
tip_off_App.post('/comment', async (req, res) => {
  const { blogId, parentId, commentId, commentator_id, content, reason } = req.body
  const tipOffId = v4()
  let tipRes = {
    status: 200,
    message: '举报成功！'
  }

  let rs = await tipOffCommentTable.create({
    tipOffId, blogId, parentId, commentId, commentator_id, content, reason
  })

  if (!rs) {
    tipRes.status = 500
    tipRes.message = '举报失败！'
  }

  res.send(tipRes)
})

module.exports = tip_off_App